package org.huang;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;

import java.util.Arrays;

@SpringBootApplication
@Slf4j
public class Java21Application implements ApplicationRunner, ApplicationListener<ApplicationEvent>, DisposableBean {

    // SpringBoot事件 1.实现 ApplicationListener  2. 实现 SpringApplicationRunListener  3.@EventListener
    public static void main(String[] args) {

        //springboot2.5  系统环境变量指定前缀 huang-name huang-age
        //Spring Boot 2.6 默认禁止循环依赖
        SpringApplication application = new SpringApplication(Java21Application.class);

        application.setEnvironmentPrefix("huang");
        application.setAllowCircularReferences(false);

        ConfigurableApplicationContext context = application.run(args);
        String[] activeProfiles = context.getEnvironment().getActiveProfiles();

        log.error("Java21Application start success! profile : {}", Arrays.toString(activeProfiles));

    }


    @EventListener
    public void starting(ApplicationReadyEvent event) {
        //log.error("ApplicationReadyEvent: {}", event.toString());
    }


    //! PostConstruct -> ApplicationStartedEvent-> ApplicationReadyEvent -> ApplicationRunner -> CommandLineRunner
    //! ContextClosedEvent -> preDestroy -> DisposableBean
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("ApplicationRunner running! args = {}", Arrays.asList(args.getSourceArgs()));
    }

    @PostConstruct
    private void init(){
        //log.error("PostConstruct");
    }


    @Override
    public void destroy(){
        log.error("DisposableBean!");
    }

    @PreDestroy
    private void preDestroy(){
        //log.error("preDestroy");
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        //log.error("ApplicationEvent: {}", event.toString());
    }

}
